<template>
  <a-select
    :value="selectValue"
    :placeholder="placeholder"
    :options="options"
    :loading="loading"
    v-bind="$attrs"
    @update:value="handleChange"
  />
</template>

<script lang="ts" setup>
import { computed, watch, ref } from 'vue';
import { useDictData } from '@/hooks/useDictData';
import type { SelectValue } from 'ant-design-vue/es/select';

const props = defineProps({
  dictCode: {
    type: String,
    required: true,
    description: '字典类型编码',
  },
  modelValue: {
    type: [String, Number, Array],
    default: undefined,
    description: '当前选中值',
  },
  placeholder: {
    type: String,
    default: '请选择',
    description: '占位文本',
  },
  valueType: {
    type: String,
    default: 'string', // 可选 'string', 'number'
    description: '值类型转换，可以是字符串或数字',
  },
  filterStatus: {
    type: Boolean,
    default: true,
    description: '是否过滤已禁用的选项',
  },
  mode: {
    type: String as () => 'multiple' | 'tags' | 'combobox' | undefined, 
    default: undefined,
    description: '设置 Select 的模式',
  }
});

const emit = defineEmits(['update:modelValue', 'change']);

// 处理值类型，确保与SelectValue兼容
const selectValue = computed<SelectValue>(() => {
  // 如果是数组模式
  if (props.mode === 'multiple' || props.mode === 'tags') {
    if (Array.isArray(props.modelValue)) {
      return props.modelValue as string[] | number[];
    }
    return [];
  }
  
  // 单选模式
  if (props.modelValue === undefined || props.modelValue === null) {
    return undefined;
  }
  
  return props.modelValue as string | number;
});

// 加载字典数据
const { dictOptions, loading, refresh } = useDictData(props.dictCode);

// 处理选项数据，根据filterStatus过滤已禁用的选项
const options = computed(() => {
  let result = dictOptions.value;
  
  // 过滤禁用状态的选项(status为0表示禁用)
  if (props.filterStatus) {
    result = result.filter(item => item.status !== 0);
  }
  
  // 根据valueType转换value类型
  return result.map(item => {
    let value = item.value;
    if (props.valueType === 'number' && typeof value === 'string') {
      value = isNaN(Number(value)) ? value : Number(value);
    } else if (props.valueType === 'string' && typeof value === 'number') {
      value = String(value);
    }
    
    return {
      ...item,
      value
    };
  });
});

// 处理值变更
const handleChange = (val: SelectValue) => {
  emit('update:modelValue', val);
  emit('change', val);
};

// 监听dictCode变化，重新加载数据
watch(() => props.dictCode, () => {
  if (props.dictCode) {
    refresh();
  }
});
</script> 